package com.jmodata.zxu.interceptor;

import com.jmodata.zxu.pojo.manager.LoginLog;
import com.jmodata.zxu.pojo.manager.Manager;
import com.jmodata.zxu.service.manager.LoginLogService;
import com.jmodata.zxu.service.manager.ManagerService;
import com.jmodata.zxu.utils.StringOrDate.MD5;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

public class LoginLogInterceptor extends HandlerInterceptorAdapter {

	@Autowired(required = false)
	private ManagerService managerService;
	@Autowired(required = false)
	private LoginLogService loginLogService;
	
	private Logger logger = Logger.getLogger(LoginLogInterceptor.class);
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String url = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/"));
		if(!url.equals("/managerLogin"))
		{
			return true;
		}
		logger.info("认证日志--开始");
		String ip=request.getHeader("x-forwarded-for");
		 if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
		        ip = request.getHeader("Proxy-Client-IP");
		    }
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
		        ip = request.getHeader("WL-Proxy-Client-IP");
		    }
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
		        ip = request.getRemoteAddr();
		    }
		    ip=(ip.equals("0:0:0:0:0:0:0:1"))?"127.0.0.1":ip;
			try {
				Manager mgr = managerService.getManagerLogin(request.getParameter("username"), new MD5().hexString(request.getParameter("password"), Charset.forName("UTF-8")));
				if(mgr == null)
				{
					return true;
				}
				if ("0".equals(mgr.getStatus()+"")) {
					LoginLog loginLog=new LoginLog();
					loginLog.setLoginAddress(ip);
					loginLog.setUserId(mgr.getManager_id().longValue());
					Integer count= loginLogService.insertLoginLog(loginLog);
					if(count == 0)
					{
						logger.info("---认证日志---新增失败！！");
					}
					logger.info("---认证日志---新增成功！！");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("---认证日志---新增失败！！");
				return true;
			}
		logger.info("认证日志--结束");
		return true;
	}

}
